package com.ztf0337.mycurriculumdesign.ui.fragment;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ztf0337.mycurriculumdesign.R;
import com.ztf0337.mycurriculumdesign.adapter.OrderAdapter;
import com.ztf0337.mycurriculumdesign.entity.Order;
import com.ztf0337.mycurriculumdesign.service.OrderService;
import com.ztf0337.mycurriculumdesign.ui.activity.OrderDetailActivity;

import java.util.List;

public class OrderFragment  extends Fragment {

    private RecyclerView rvOrder;
    private OrderAdapter adapter;
    private List<Order> orderList;
    private Context context;
    private OrderService orderService;
    private ImageView ic_more,ic_filter,ic_delete,ic_affirm,ic_cansel,ic_Search;
    private EditText etSearch;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order, container, false);
        context = getContext();
        if (context == null) {
            return view;
        }

        rvOrder = view.findViewById(R.id.rvOrder);
        rvOrder.setLayoutManager(new LinearLayoutManager(getContext()));
        SharedPreferences loginInfo = context.getSharedPreferences("loginInfo", Context.MODE_PRIVATE);
        orderService = new OrderService(context);

        ic_filter = requireActivity().findViewById(R.id.ic_filter);
        ic_filter.setVisibility(GONE);
        ic_delete = requireActivity().findViewById(R.id.ic_delete);
        ic_delete.setVisibility(GONE);
        ic_affirm = requireActivity().findViewById(R.id.ic_affirm);
        ic_affirm.setVisibility(GONE);
        ic_cansel = requireActivity().findViewById(R.id.ic_cansel);
        ic_cansel.setVisibility(GONE);
        ic_more = requireActivity().findViewById(R.id.ic_more);
        etSearch = requireActivity().findViewById(R.id.etSearch);
        etSearch.setText(""); // 清空内容
        ic_Search = requireActivity().findViewById(R.id.ic_Search);

        TextView notOrder = view.findViewById(R.id.notOrder);

        LinearLayout searchLayout = requireActivity().findViewById(R.id.search);
        searchLayout.setVisibility(GONE);

        if (!loginInfo.getBoolean("login",false)) {
            notOrder.setText("未登录");
            notOrder.setVisibility(VISIBLE);
        } else {
            orderList = orderService.getOrdersByUserId(loginInfo.getLong("user_id",-1L));
            if (!orderList.isEmpty()) {
                searchLayout.setVisibility(VISIBLE);
                notOrder.setVisibility(GONE);
                adapter = new OrderAdapter(orderList);
                rvOrder.setAdapter(adapter);
                adapter.setOnItemClickListener((order) -> {
                    Intent intent = new Intent(context, OrderDetailActivity.class);
                    intent.putExtra("id", order.getId());
                    context.startActivity(intent);
                });
                ic_more.setVisibility(VISIBLE);
            } else {
                ic_more.setVisibility(GONE);
                notOrder.setText("无订单信息");
                notOrder.setVisibility(VISIBLE);
            }
        }

        etSearch.setHint("请输入车位号或订单号");
        ic_Search.setOnClickListener(v -> {
            String search = etSearch.getText().toString().trim();
            ic_cansel.setVisibility(GONE);
            ic_filter.setVisibility(GONE);
            ic_delete.setVisibility(GONE);
            ic_affirm.setVisibility(GONE);
            ic_more.setVisibility(VISIBLE);
            if (search.isBlank()) {
                if (orderList.isEmpty()) {
                    Toast.makeText(context, "无订单信息", Toast.LENGTH_SHORT).show();
                } else {
                    adapter.updateData(orderList);
                }
                return;
            }
            List<Order> orders = orderService.searchOrders(search,loginInfo.getLong("user_id",-1L));
            if (orders.isEmpty()) {
                Toast.makeText(context, "无符合条件的订单", Toast.LENGTH_SHORT).show();
            } else {
                adapter.updateData(orders);
            }
        });


        ic_more.setOnClickListener(v -> {
            if (ic_filter.getVisibility() != View.VISIBLE) {
                ic_filter.setVisibility(VISIBLE);
                ic_delete.setVisibility(VISIBLE);
            } else {
                ic_filter.setVisibility(GONE);
                ic_delete.setVisibility(GONE);
            }
        });

        ic_delete.setOnClickListener(v -> {
            ic_filter.setVisibility(GONE);
            ic_more.setVisibility(GONE);
            ic_delete.setVisibility(GONE);
            ic_affirm.setVisibility(VISIBLE);
            ic_cansel.setVisibility(VISIBLE);
            ic_Search.setVisibility(GONE);
            adapter.setSelectionMode(true);

            ic_cansel.setOnClickListener(v1 -> {
                ic_more.setVisibility(VISIBLE);
                ic_affirm.setVisibility(GONE);
                ic_cansel.setVisibility(GONE);
                ic_filter.setVisibility(VISIBLE);
                ic_delete.setVisibility(VISIBLE);
                ic_Search.setVisibility(VISIBLE);
                adapter.setSelectionMode(false);
                adapter.clearSelect();
            });

            ic_affirm.setOnClickListener(v2 -> {
                ic_more.setVisibility(VISIBLE);
                ic_affirm.setVisibility(GONE);
                ic_cansel.setVisibility(GONE);
                ic_Search.setVisibility(VISIBLE);
                adapter.setSelectionMode(false);
                //执行删除
                List<Order> selectOrderIds = adapter.getSelectOrdersAndClear();
                for (Order i :selectOrderIds) {
                    orderService.delete(i);
                    adapter.removeItem(i);
                    Log.d("删除","订单 "+i.getId());
                }
                Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
            });
        });



        ic_filter.setOnClickListener(v -> {
            orderFilter(loginInfo.getLong("user_id",-1L));
        });
        return view;
    }

    private void orderFilter(Long userId) {
        View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_order_filter, null);

        RadioGroup statusGroup = dialogView.findViewById(R.id.statusGroup);
        RadioGroup typeGroup = dialogView.findViewById(R.id.typeGroup);
        RadioGroup dateGroup = dialogView.findViewById(R.id.dateGroup);


        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setView(dialogView)
                .setTitle("筛选条件")
                .setPositiveButton("确认", (dialog, which) -> {

                    int statusId = statusGroup.getCheckedRadioButtonId();
                    int typeId = typeGroup.getCheckedRadioButtonId();
                    int dateId = dateGroup.getCheckedRadioButtonId();


                    int status = 0,type = 0,date = 0;

                    if (statusId == R.id.radioStatusIdle) {
                        status = 1;
                    } else if (statusId == R.id.radioStatusOccupied) {
                        status = 2;
                    }

                    if (typeId == R.id.radioSmallElectric) {
                        type = 1;
                    } else if (typeId == R.id.radioMediumElectric) {
                        type = 2;
                    } else if (typeId == R.id.radioLargeElectric) {
                        type = 3;
                    } else if (typeId == R.id.radioSmallFuel) {
                        type = 4;
                    } else if (typeId == R.id.radioMediumFuel) {
                        type = 5;
                    } else if (typeId == R.id.radioLargeFuel) {
                        type = 6;
                    }

                    if (dateId == R.id.radioNO) {
                        date = 1;
                    } else if (dateId == R.id.radioON) {
                        date = 2;
                    }
                    Log.d("反转测试","先择的操作"+date);
                    ic_more.setVisibility(GONE);
                    ic_affirm.setVisibility(GONE);
                    ic_cansel.setVisibility(VISIBLE);
                    ic_filter.setVisibility(GONE);
                    ic_delete.setVisibility(GONE);

                    ic_cansel.setOnClickListener(v1 -> {
                        if (!orderList.isEmpty()) {
                            adapter.updateData(orderList);
                        }
                        ic_cansel.setVisibility(GONE);
                        ic_more.setVisibility(VISIBLE);
                        Toast.makeText(context, "已取消筛选", Toast.LENGTH_SHORT).show();
                    });
                    // 调用筛选函数
                    filterData(status, type, date, userId);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void filterData(int status, int type, int date, Long userId) {
        List<Order> orders = orderService.filterData(status, type, date, userId);
        if (orders.isEmpty()) {
            Toast.makeText(context, "无符合条件的车位", Toast.LENGTH_SHORT).show();
        } else {
            adapter.updateData(orders);
            Toast.makeText(context, "已筛选", Toast.LENGTH_SHORT).show();

        }

    }
}
